package com.didispace.chapter310;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: gx.wu
 * @create: 2023-03-20 09:51
 * @Description:
 */
@Slf4j
@Service
public class GoodsService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private GoodsDao goodsDao;


    public void insert00Normal(Goods goods){
        log.info("### goods：{}", goods);
        Goods r = goodsRepository.save(goods);
        log.info("### goods：{}", goods);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void insert01(Goods goods){
        log.info("### goods：{}", goods);
        Goods r = goodsRepository.save(goods);
        log.info("### goods：{}", goods);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void insert02RuntimeException(Goods goods){
        log.info("### goods：{}", goods);
        Goods r = goodsRepository.save(goods);
        log.info("### goods：{}", goods);
        throw new RuntimeException("抛出异常!");
    }

    @Transactional(propagation =  Propagation.SUPPORTS)
    public void insert03SupportRuntimeException(Goods goods){
        log.info("### goods：{}", goods);
        Goods r = goodsRepository.save(goods);
        log.info("### goods：{}", goods);
        throw new RuntimeException("抛出异常!");
    }

    @Transactional(propagation =  Propagation.MANDATORY)
    public void insert04MandatoryRuntimeException(Goods goods){
        log.info("### goods：{}", goods);
        Goods r = goodsRepository.save(goods);
        log.info("### goods：{}", goods);
        throw new RuntimeException("抛出异常!");
    }


    @Transactional(propagation =  Propagation.NESTED)
    public void insert05NestedNormal(Goods goods){
        log.info("### goods：{}", goods);
        int r = goodsDao.save(goods);   //Jpa不支持nested，改为JDBCTemplate
        log.info("### goods：{}", goods);
    }

    @Transactional(propagation =  Propagation.NESTED)
    public void insert06NestedRuntimeException(Goods goods){
        log.info("### goods：{}", goods);
        int r = goodsDao.save(goods);   //Jpa不支持nested，改为JDBCTemplate
        log.info("### goods：{}", goods);
        throw new RuntimeException("抛出异常!");
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insert07RequiresNewRuntimeException(Goods goods){
        log.info("### goods：{}", goods);
        Goods r = goodsRepository.save(goods);
        log.info("### goods：{}", goods);
        throw new RuntimeException("抛出异常!");
    }

}
